package com.bai.localshop.interceptor;

import com.bai.localshop.context.BaseContext;
import com.bai.localshop.properties.JwtProperties;
import com.bai.localshop.service.AuthService;
import com.bai.localshop.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthService authService; // 注入用户服务

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 统一使用用户token名称
        String token = request.getHeader(jwtProperties.getUserTokenName());

        if (token == null || token.trim().isEmpty()) {
            response.setStatus(401);
            return false;
        }

        try {
            log.info("jwt校验:{}", token);

            // 统一使用用户密钥解析
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get("userId").toString());

            // 如果是管理员路径，检查用户角色
            String requestURI = request.getRequestURI();
            if (requestURI.startsWith("/admin/")) {
                if (!authService.isAdmin(userId)) {
                    log.warn("用户{}无权限访问管理员接口: {}", userId, requestURI);
                    response.setStatus(403); // 无权限
                    return false;
                }
            }

            BaseContext.setCurrentId(userId);
            log.info("当前用户id：{}", userId);
            return true;
        } catch (Exception ex) {
            log.error("JWT校验失败: {}", ex.getMessage());
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        BaseContext.removeCurrentId();
    }
}
